package esb.chapter4.messageflow.servicemix;

import javax.annotation.Resource;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import javax.xml.transform.Source;

import org.apache.log4j.Logger;
import org.apache.servicemix.MessageExchangeListener;
import org.apache.servicemix.components.util.ComponentSupport;
import org.apache.servicemix.jbi.jaxp.SourceTransformer;
import org.apache.servicemix.jbi.jaxp.StringSource;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import esb.chapter4.messageflow.domain.BookQuote;
import esb.chapter4.messageflow.service.util.QuoteMessageHelper;

public class CheapestPriceCalculator extends ComponentSupport implements MessageExchangeListener {

	private static final Logger logger = Logger.getLogger(CheapestPriceCalculator.class);
	private SourceTransformer sourceTransformer = new SourceTransformer();
	@Resource
	private DeliveryChannel channel;

    public void onMessageExchange(MessageExchange exchange) throws MessagingException {
    	if (exchange.getStatus() != ExchangeStatus.ACTIVE) {
    		logger.info("state is not active so ignoring call");
    		return;
    	}
    	Element payloadElem = null;
    	Source contentSource = null;
    	try {
    		contentSource = getInMessage(exchange).getContent();
    		payloadElem = sourceTransformer.toDOMElement(contentSource);
        } catch(Exception e) {
        	logger.error("error while reading payload", e);
        }
        BookQuote cheapestQuote = null;
        NodeList aggregateList = payloadElem.getChildNodes();
        for(int i = 0; i < aggregateList.getLength(); i++) {
        	Node aggregateNode = aggregateList.item(i);
        	Node childNode = aggregateNode.getFirstChild();
    		BookQuote bookQuote = QuoteMessageHelper.unmarshallQuote(childNode);
    		if(cheapestQuote == null || bookQuote.getPrice().floatValue() < 
    				cheapestQuote.getPrice().floatValue()) {
    			cheapestQuote = bookQuote;
    		}
        }
    	NormalizedMessage outMessage = exchange.createMessage();
    	try {
    		outMessage.setContent(new StringSource(QuoteMessageHelper.marshallQuote(cheapestQuote)));
    	} catch(Exception e) {
    		logger.error("error setting content on cheapest bookstore response message", e);
    	}
        exchange.setMessage(outMessage, "out");
        channel.send(exchange);
    }
}
